package com.hulk.dryad.admin.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.hulk.dryad.admin.api.vo.SysFileVO;
import com.hulk.dryad.admin.mapstruct.SysFileStruct;
import com.hulk.dryad.common.annotation.Idempotent;
import com.hulk.dryad.common.annotation.OperLog;
import com.hulk.dryad.common.annotation.PrintlnLog;
import com.hulk.dryad.common.component.R;
import com.hulk.dryad.common.constant.enums.ActionType;
import com.hulk.dryad.manage.framework.storage.Storage;
import com.hulk.dryad.manage.framework.tenant.TenantHierarchyUtil;
import com.hulk.dryad.manage.provider.transaction.S3FsTransaction;
import com.hulk.dryad.persistence.entity.SysFileModel;
import com.hulk.dryad.manage.provider.service.SysFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件管理
 *
 * @author kim
 * @date 2019-06-18 17:18:42
 */
@Slf4j
@ApiSort(8)
@Api(value = "sys-file", tags = "文件管理")
@RestController
@RequestMapping("/admin/sys-file")
@RequiredArgsConstructor
public class SysFileController {


	private final SysFileService sysFileService;
	private final S3FsTransaction s3FsTransaction;
	private final Storage storageTemplate;


	/**
	 * 分页查询
	 * @param page 分页对象
	 * @param sysFile 文件管理
	 * @return
	 */
	@ApiOperation(value = "getSysFilePage", notes = "分页查询")
	@PrintlnLog
	@GetMapping("/page")
	public R getSysFilePage( Page page, SysFileVO sysFile) {
		SysFileStruct INSTANCE = SysFileStruct.INSTANCE;
		SysFileModel model = INSTANCE.to(sysFile);
		Page<SysFileModel>  rpm =sysFileService.page(page, Wrappers.query(model));
		Page<SysFileVO> rpv= INSTANCE.from(rpm);
		return R.ok(rpv);
	}

	/**
	 * 通过id删除文件管理
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "removeById", notes = "通过id删除文件管理")
	@OperLog(value ="删除文件管理",action = ActionType.DEL)
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('sys_file_del')")
	public R removeById(@PathVariable Long id) {
		return R.ok(s3FsTransaction.deleteFile(id));
	}

	/**
	 * 上传文件 文件名采用uuid,避免原始文件名中带"-"符号导致下载的时候解析出现异常
	 * @param file 资源
	 * @return R(/ admin / bucketName / filename)
	 */

	@SneakyThrows
	@ApiOperation(value = "upload", notes = "上传文件")
	@Idempotent
	@OperLog(value ="上传文件",action = ActionType.ADD)
	@PostMapping("/upload")
	@PreAuthorize("@pms.hasPermission('sys_file_add')")
	public R upload(@RequestPart("file") MultipartFile file) {

		String yyyyMM =  LocalDateTimeUtil.format(LocalDateTime.now(), DatePattern.SIMPLE_MONTH_PATTERN);
		String tenantId  = TenantHierarchyUtil.getTenantId();
		String directory = Paths.get(tenantId,yyyyMM).toString();
		String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileNameUtil.extName(file.getOriginalFilename());
	    String bucket = storageTemplate.getProp().getBucket();
		storageTemplate.store(file.getInputStream(), file.getContentType(), fileName,  directory,  bucket);
		String domain = storageTemplate.getHost(fileName,directory,bucket);
		sysFileService.uploadFile(file,domain,fileName,directory,bucket);
		Map<String, String> resultMap = new HashMap<>(4);
		resultMap.put("fileName", fileName);
		resultMap.put("directory", directory);
		resultMap.put("bucketName", bucket);
		resultMap.put("uri", storageTemplate.generateUri(fileName,directory,bucket));
		resultMap.put("host", storageTemplate.getHost( fileName,  directory,  bucket));
		return R.ok(resultMap);
	}

	/**
	 * 获取文件
	 * @param id 记录id
     * @param request
	 * @param response
	 * @return
	 */
	@PrintlnLog
	@ApiOperation(value = "getFile", notes = "获取文件")
	@GetMapping("/download/{id}")
	public void fileDownLoad(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response) {
		SysFileModel file = sysFileService.getById(id);
		String fileName = file.getFileName();
		String directory = file.getFileDir();
		String bucket = file.getBucketName();
		try (InputStream  inputStream = storageTemplate.loadAsInputStream(fileName,directory,bucket)) {
			response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
			IoUtil.copy(inputStream, response.getOutputStream());
		}
		catch (Exception e) {
			log.error("文件读取异常: {}", e.getLocalizedMessage());
		}
	}

}
